'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  TextField, 
  Button, 
  Card, 
  CardContent, 
  Typography, 
  Box, 
  Alert, 
  CircularProgress,
  InputAdornment
} from '@mui/material';

export default function LoginWithPhonePage() {
  const router = useRouter();
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [countdown, setCountdown] = useState(0);
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [error, setError] = useState('');

  const validatePhone = () => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phone) {
      setError('请输入手机号');
      return false;
    }
    if (!phoneRegex.test(phone)) {
      setError('请输入有效的手机号');
      return false;
    }
    return true;
  };

  const handleSendCode = async () => {
    if (!validatePhone()) return;

    setSendingCode(true);
    setError('');

    try {
      const response = await fetch('/api/auth/send-verification-code', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          phone,
          purpose: 'registration' // 复用注册验证码类型
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '发送验证码失败');
      }

      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      // 在开发环境中，如果返回了验证码，自动填充
      if (process.env.NODE_ENV === 'development' && data.code) {
        setCode(data.code);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '发送验证码失败');
    } finally {
      setSendingCode(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validatePhone()) return;
    
    if (!code) {
      setError('请输入验证码');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/auth/login-with-phone', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, code }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '登录失败');
      }

      // 保存登录信息
      localStorage.setItem('token', data.token);
      localStorage.setItem('user', JSON.stringify(data.user));
      
      // 跳转到首页
      router.push('/');
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录过程中发生错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        bgcolor: 'background.default',
        py: 4,
      }}
    >
      <Card sx={{ maxWidth: 400, width: '100%', mx: 2 }}>
        <CardContent sx={{ p: 4 }}>
          <Typography variant="h4" component="h1" align="center" gutterBottom>
            手机号登录
          </Typography>
          
          <form onSubmit={handleSubmit}>
            <TextField
              fullWidth
              label="手机号"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              margin="normal"
              required
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <Button
                      onClick={handleSendCode}
                      disabled={countdown > 0 || sendingCode}
                      sx={{ whiteSpace: 'nowrap' }}
                    >
                      {sendingCode ? (
                        <CircularProgress size={24} />
                      ) : countdown > 0 ? (
                        `${countdown}秒后重发`
                      ) : (
                        '发送验证码'
                      )}
                    </Button>
                  </InputAdornment>
                ),
              }}
            />
            
            <TextField
              fullWidth
              label="验证码"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              margin="normal"
              required
            />

            {error && (
              <Alert severity="error" sx={{ mt: 2 }}>
                {error}
              </Alert>
            )}

            <Button
              fullWidth
              type="submit"
              variant="contained"
              size="large"
              sx={{ mt: 3 }}
              disabled={loading}
            >
              {loading ? <CircularProgress size={24} /> : '登录'}
            </Button>

            <Box sx={{ mt: 2, textAlign: 'center' }}>
              <Link href="/auth/reset-password-with-phone" style={{ textDecoration: 'none' }}>
                <Typography color="primary" sx={{ mb: 1, display: 'inline-block' }}>
                  忘记密码？
                </Typography>
              </Link>
              <br />
              <Link href="/auth/register-with-phone" style={{ textDecoration: 'none' }}>
                <Typography color="primary" sx={{ display: 'inline-block' }}>
                  还没有账号？立即注册
                </Typography>
              </Link>
              <br />
              <Link href="/auth/login" style={{ textDecoration: 'none' }}>
                <Typography color="primary" sx={{ mt: 1, display: 'inline-block' }}>
                  使用账号密码登录
                </Typography>
              </Link>
            </Box>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
}
